package com.xoa.dev.jinOuWorkFlowWebService.com.weaver.docs;

import com.xoa.dev.jinOuWorkFlowWebService.localhost.services.DocService.DocServiceLocator;
import com.xoa.dev.jinOuWorkFlowWebService.localhost.services.DocService.DocServicePortType;
import com.xoa.dev.jinOuWorkFlowWebService.util.GdPara;
import com.xoa.dev.jinOuWorkFlowWebService.weaver.docs.webservices.DocAttachment;
import com.xoa.dev.jinOuWorkFlowWebService.weaver.docs.webservices.DocInfo;
import org.apache.axis.encoding.Base64;

import javax.xml.rpc.ServiceException;
import java.io.*;
import java.net.URL;
import java.util.zip.ZipInputStream;


public class DownloadDoc {
    public static void main(String[] args) throws IOException {
        DocServiceLocator docServiceLocator = new DocServiceLocator();

        try {
            //根据Eclipse生成的Web Service客户端程序，取得接口
            DocServicePortType service = docServiceLocator.getDocServiceHttpPort(new URL(GdPara.url));
            String session = service.login("02014003", "1", 0, GdPara.ip);
            System.out.println(session);
//            DocInfo[] docInfos = service.getList(session, 1, 1);
//            System.out.println(session);
//            DocInfo docInfo = service.getDoc(1, session);
            //根据ID取得文档内容
            DocInfo docInfo = service.getDoc(98822, session);
            //附件
            DocAttachment[] doc = docInfo.getAttachments();


            for (DocAttachment da : doc) {
                //得到附件内容
                byte[] content = Base64.decode(da.getFilecontent());
                File file = new File("e:\\" + da.getFilename());
                InputStream imagefile = null;
                OutputStream out = null;
                try {

                    int byteread = 0;
                    byte data[] = new byte[1024];
                    if (da.getIszip() == 0) {
                        ZipInputStream zin = new ZipInputStream(new FileInputStream(new File(da.getFilerealpath())));
                        if (zin.getNextEntry() != null)
                            imagefile = new BufferedInputStream(zin);
                    } else {
                        imagefile = new ByteArrayInputStream(content);
                    }
                    out = new FileOutputStream(file);
                    while ((byteread = imagefile.read(data)) != -1) {
                        out.write(data, 0, byteread);
                        out.flush();
                    }
                    imagefile.close();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
}